package box2d_cgo

/*
#cgo LDFLAGS: -L . -lgobox2d -lBox2D
#cgo CFLAGS: -I ./
#include "box2d.h"
*/
import "C"
import (
	"unsafe"
)

//export go_BeginContact
func go_BeginContact(pGoListener unsafe.Pointer, pContact unsafe.Pointer) {
	listener := (*B2ContactListener)(pGoListener)
	listener.DispatchBeginContact(pContact)
}

//export go_EndContact
func go_EndContact(pGoListener unsafe.Pointer, pContact unsafe.Pointer) {
	listener := (*B2ContactListener)(pGoListener)
	listener.DispatchEndContact(pContact)
}

type ContactFunc func(B2Contact)
type B2ContactListener struct {
	Ptr               unsafe.Pointer
	BeginContactFuncs []ContactFunc
	EndContactFuncs   []ContactFunc
}

func NewB2ContactListener() *B2ContactListener {
	newListener := &B2ContactListener{}
	newListener.Ptr = C.NewGoContactListener(unsafe.Pointer(newListener))
	return newListener
}

func (this *B2ContactListener) DispatchBeginContact(pContact unsafe.Pointer) {
	Contact := B2Contact(pContact)
	for i := 0; i < len(this.BeginContactFuncs); i++ {
		this.BeginContactFuncs[i](Contact)
	}
}

func (this *B2ContactListener) DispatchEndContact(pContact unsafe.Pointer) {
	Contact := B2Contact(pContact)
	for i := 0; i < len(this.EndContactFuncs); i++ {
		this.EndContactFuncs[i](Contact)
	}
}

func (this *B2ContactListener) AddBeginContactEvent(fn ContactFunc) {
	this.BeginContactFuncs = append(this.BeginContactFuncs, fn)
}

func (this *B2ContactListener) AddEndContactEvent(fn ContactFunc) {
	this.EndContactFuncs = append(this.EndContactFuncs, fn)
}
